import 'dart:developer';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kasax/commons/commons.dart';
import 'package:kasax_demos2/entry/data_posts_test.dart';
import 'package:kasax_demos2/gankio/widget/refreshale_widget.dart';
import 'package:kasax_demos2/testhelper/gankio/gank_provider.dart';
import 'package:kasax_demos2/widgets/image_widget.dart';

import 'entry/girl_category_result_entity.dart';
import 'entry/girl_sub_category_result_entity.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

/// 子类界面
class MzSubCategoryListPage extends StatefulWidget {
  String category;

  MzSubCategoryListPage(this.category, {Key? key}) : super(key: key);

  @override
  _MzSubCategoryListPageState createState() => _MzSubCategoryListPageState();
}

class _MzSubCategoryListPageState extends State<MzSubCategoryListPage> {
  List<GirlCategoryResultData> datas = <GirlCategoryResultData>[];
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    // log("_MzSubCategoryListPageState: ${widget.category}");
    loadMzList();
  }

  @override
  Widget build(BuildContext context) {
    return buildExpanded();
  }

  Expanded buildExpanded() {
    /// 局部刷新可以使用bloc,provider替换
    var _refreshableView = RefreshableView(
      builder: (context) {
        return datas == null || datas.isEmpty
            ? buildLoadingWidget()
            : MzCategoryTypeList(widget.category, datas[_currentIndex]);
      },
    );
    return Expanded(
        child: Container(
      margin: EdgeInsets.only(left: 3.0),
      width: double.infinity,
      child: Column(
        children: [
          Container(
            color: Colors.green,
            height: 55,
            child: buildTabListView(_refreshableView),
          ),
          Expanded(
              child: Container(
            padding: EdgeInsets.only(top: 8, bottom: 8),
            color: Colors.grey[20],
            child: _refreshableView,
          ))
        ],
      ),
    ));
  }

  ListView buildTabListView(RefreshableView _refreshableView) {
    return ListView.separated(
        scrollDirection: Axis.horizontal,
        itemBuilder: (context, index) {
          return Padding(
            padding: EdgeInsets.only(
              left: 5,
              right: 5,
            ),
            child: Container(
              alignment: Alignment.center,
              child: FlatButton(
                onPressed: () {
                  setState(() {
                    _currentIndex = index;
                    _refreshableView.reload();
                  });
                },
                child: Text(
                  datas[index].title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color:
                          _currentIndex == index ? Colors.lightBlueAccent : Colors.white),
                ),
              ),
            ),
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
        itemCount: datas.length);
  }

  void loadMzList() async {
    var data =
        await GankIoApiProvider.getInstance().featCategories(widget.category);
    setState(() {
      datas = data.data;
      // log("datas: $datas , data.len: ${datas.length}");
    });
  }
}

/// 类别的列表
class MzCategoryTypeList extends StatefulWidget {
  final String parentCategory;
  final GirlCategoryResultData data;

  const MzCategoryTypeList(this.parentCategory, this.data, {Key? key})
      : super(key: key);

  @override
  _MzCategoryTypeListState createState() => _MzCategoryTypeListState();
}

class _MzCategoryTypeListState extends State<MzCategoryTypeList> {
  // 一页20条数据
  final int pageSize = 20;
  int currentPage = 1;

  /// 所有列表数据
  List<GirlSubCategoryResultData> _datas = [];

  @override
  void initState() {
    super.initState();
    // log("_MzCategoryTypeListState initState: ${widget.data} , ${widget.parentCategory}");
    fetchDefDataList();
  }

  @override
  Widget build(BuildContext context) {
    var random = Random();
    return _datas == null || _datas.isEmpty
        ? buildLoadingWidget()
        : buildStaggeredGridView(random);
  }

  /// 瀑布流
  StaggeredGridView buildStaggeredGridView(Random random) {
    return StaggeredGridView.countBuilder(
      itemCount: _datas.length,
      crossAxisCount: 4,
      itemBuilder: (context, index) {
        return Container(
          child: ClipRRect(
            borderRadius: BorderRadius.circular(12),
            child: AspectRatio(
              aspectRatio: 4 / 3,
              child: Image.network(
                PostsDatas
                    .TEST_POSTS[
                        random.nextInt(PostsDatas.TEST_POSTS.length - 1) %
                            PostsDatas.TEST_POSTS.length]
                    .imageUrl,
                fit: BoxFit.fill,
              ),
            ),
          ),
        );
      },
      // staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
      staggeredTileBuilder: (int index) =>
          StaggeredTile.count(2, index.isEven ? 2.5 : 3),
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
    );
  }

  ListView buildDefListView(Random random) {
    return ListView.separated(
      itemBuilder: (context, index) {
        var e = _datas[index];
        return AspectRatio(
          aspectRatio: 4 / 3,
          child: ImgWidget(
              PostsDatas
                  .TEST_POSTS[random.nextInt(PostsDatas.TEST_POSTS.length - 1) %
                      PostsDatas.TEST_POSTS.length]
                  .imageUrl,
              ""),
        );
      },
      itemCount: _datas.length,
      separatorBuilder: (context, index) {
        return Divider();
      },
    );
  }

  buildContentItem(GirlSubCategoryResultData e, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10),
      child: Row(
        children: [
          Container(
            width: 30,
            height: 30,
            margin: EdgeInsets.only(right: 5),
            child: e.images == null || e.images.isEmpty
                ? CircularProgressIndicator()
                : CircleAvatar(
                    backgroundImage: NetworkImage(PostsDatas
                        .TEST_POSTS[index % PostsDatas.TEST_POSTS.length]
                        .imageUrl)),
          ),
          Expanded(
              child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("作者：${e.author}",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    textAlign: TextAlign.end),
                SizedBox(
                  height: 5,
                ),
                Text("${e.publishedAt}",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    textAlign: TextAlign.end),
              ],
            ),
          ))
        ],
      ),
    );
  }

  void fetchDefDataList() async {
    currentPage = 1;
    var data = await GankIoApiProvider.getInstance().featBatchCategory(
        widget.parentCategory, widget.data.type, currentPage, pageSize);
    // log("fetchListByTag data: $data , dataSize = ${data.data.length}");
    setState(() {
      _datas.addAll(data.data);
    });
  }
}
